package kadledav.portlet.news;

import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.xml.namespace.QName;

import kadledav.backend.dto.NewsDTO;
import kadledav.backend.service.NewsService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

@Controller
@RequestMapping("VIEW")
public class NewsViewController {

	private static final Logger logger = Logger.getLogger(NewsViewController.class);

	public static final int MAX_LENGHT = 35;
	public static final int MAX_MSGS = 10;

	@Autowired
	private NewsService newsService;
	
	@RenderMapping
	public ModelAndView doDefaultRender(RenderRequest request) {
		ModelAndView modelAndView = new ModelAndView(NewsConstants.JSP_VIEW);
		logger.info("News view default rendered.");
		List<NewsDTO> allNews = makeNewsShort(newsService.getNewsByDateDesc(MAX_MSGS));
		logger.debug("allNews size is " + allNews.size());
		request.setAttribute("allNews", allNews);
		return modelAndView;
	}

	private List<NewsDTO> makeNewsShort(List<NewsDTO> allNews) {
		List<NewsDTO> shortNews = new ArrayList<NewsDTO>(allNews.size());
		for (NewsDTO newsDTO : allNews) {
			if (newsDTO.getMessage().length() > MAX_LENGHT) {
				String shortMsg = newsDTO.getMessage().substring(0, MAX_LENGHT - 4) + "...";
				newsDTO.setMessage(shortMsg);
			}
			shortNews.add(newsDTO);
		}
		return shortNews;
	}

	@RequestMapping(params = "action=sendId")
	public void sendNewsIdEvent(final ActionRequest request, final ActionResponse response, @RequestParam Integer newsId) {
		logger.info("sending news id event");
		QName eventName = new QName( "http://kadledav/events","news.id");
		response.setEvent(eventName, newsId.toString());
		logger.debug("event newsId sent with value - " + newsId);
	}
}
